<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <text class="block text-[56rpx] font-extrabold mb-[48rpx] text-center text-blue-600 drop-shadow">紧急联系人信息</text>
    
    <!-- 数据列表 -->
    <view v-if="!showForm" class="mb-[32rpx]">
      <view class="flex justify-between items-center mb-[24rpx]">
        <text class="text-[32rpx] font-bold">联系人列表</text>
        <nut-button 
          type="primary" 
          size="small"
          class="text-[28rpx]"
          @click="addRecord"
        >
          新增联系人
        </nut-button>
      </view>
      
      <view v-if="recordList.length === 0" class="text-center py-[80rpx] text-[28rpx] text-gray-500">
        暂无紧急联系人，点击新增联系人添加信息
      </view>
      
      <view v-else class="space-y-[24rpx]">
        <view 
          v-for="(record, index) in recordList" 
          :key="record.id || index"
          class="bg-white rounded-[16rpx] p-[24rpx] shadow-sm"
        >
          <view class="flex justify-between items-start mb-[16rpx]">
            <view>
              <text class="text-[32rpx] font-bold text-gray-800">{{ record.emerName || '未填写姓名' }}</text>
              <text class="text-[24rpx] text-gray-500 ml-[16rpx]">{{ getRelationshipText(record.relationship) }}</text>
            </view>
            <view class="flex gap-[16rpx]">
              <nut-button 
                type="primary" 
                size="mini"
                @click="editRecord(record, index)"
              >
                编辑
              </nut-button>
              <nut-button 
                type="danger" 
                size="mini"
                @click="deleteRecord(index)"
              >
                删除
              </nut-button>
            </view>
          </view>
          
          <view class="grid grid-cols-1 gap-[12rpx] text-[28rpx]">
            <view><text class="text-gray-600">联系电话：</text>{{ record.emerTel || '未填写' }}</view>
            <view><text class="text-gray-600">证件号码：</text>{{ record.idNumber || '未填写' }}</view>
            <view v-if="record.note"><text class="text-gray-600">备注：</text>{{ record.note }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 表单 -->
    <view v-if="showForm">
      <view class="flex justify-between items-center mb-[32rpx]">
        <text class="text-[32rpx] font-bold">{{ isEdit ? '编辑联系人' : '新增联系人' }}</text>
        <nut-button 
          type="default" 
          size="small"
          @click="cancelForm"
        >
          返回列表
        </nut-button>
      </view>
      
      <nut-form ref="formRef" :model="form" :rules="formRules" class="max-w-[700rpx] w-full mx-auto box-border">
        <!-- 基本信息 -->
        <view class="mb-[32rpx]">
          <text class="text-[36rpx] font-bold text-blue-600 mb-[24rpx] block">基本信息</text>
          
          <nut-form-item label="本人姓名" prop="name" class="mb-[32rpx] text-[32rpx]">
            <nut-input 
              v-model="form.name" 
              placeholder="请输入本人姓名"
              class="h-[88rpx] text-[32rpx]"
            />
          </nut-form-item>
          
          <nut-form-item label="本人证件号码" prop="idNumber" class="mb-[32rpx]">
            <nut-input 
              v-model="form.idNumber" 
              placeholder="请输入本人证件号码"
              class="h-[88rpx] text-[32rpx]"
            />
          </nut-form-item>
        </view>

        <!-- 紧急联系人信息 -->
        <view class="mb-[32rpx]">
          <text class="text-[36rpx] font-bold text-blue-600 mb-[24rpx] block">紧急联系人信息</text>
          
          <nut-form-item label="联系人姓名" prop="emerName" class="mb-[32rpx] text-[32rpx]">
            <nut-input 
              v-model="form.emerName" 
              placeholder="请输入紧急联系人姓名"
              class="h-[88rpx] text-[32rpx]"
            />
          </nut-form-item>
          
          <nut-form-item label="联系人电话" prop="emerTel" class="mb-[32rpx]">
            <nut-input 
              v-model="form.emerTel" 
              placeholder="请输入联系人电话"
              type="tel"
              class="h-[88rpx] text-[32rpx]"
              @input="onPhoneInput"
            />
            <view v-if="phoneError" class="text-[28rpx] text-red-500 mt-[12rpx]">
              {{ phoneError }}
            </view>
          </nut-form-item>
          
          <PickerInput 
            v-model="form.relationship" 
            :columns="relationshipOptions" 
            label="与本人关系" 
            prop="relationship" 
            placeholder="请选择与本人关系" 
          />
          
          <nut-form-item label="备注信息" class="mb-[32rpx]">
            <nut-textarea 
              v-model="form.note" 
              placeholder="请输入备注信息（选填）"
              rows="3"
              maxlength="200"
              show-word-limit
            />
          </nut-form-item>
        </view>
        
        <view class="mt-[48rpx] flex gap-[24rpx]">
          <nut-button 
            block 
            type="default" 
            class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1"
            @click="resetForm"
          >
            重置表单
          </nut-button>
          <nut-button 
            block 
            type="primary" 
            class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1 bg-green-500 hover:bg-green-600 active:bg-green-700"
            :loading="submitting"
            @click="submitForm"
          >
            {{ submitting ? '保存中...' : '保存信息' }}
          </nut-button>
        </view>
      </nut-form>
    </view>
  </view>
</template>

<script setup lang="ts">
import Taro from '@tarojs/taro'
import { ref, reactive } from 'vue'
import PickerInput from '@/components/PickerInput.vue'

// 表单数据
const form = ref({
  id: '',
  name: '',
  idNumber: '',
  emerName: '',
  emerTel: '',
  relationship: 1,
  note: '',
  recordid: 0,
  createBy: '',
  createTime: '',
  updateBy: '',
  updateTime: ''
})

const formRef = ref()
const submitting = ref(false)
const showForm = ref(false)
const isEdit = ref(false)
const editIndex = ref(-1)
const recordList = ref<any[]>([])
const phoneError = ref('')

// 关系选项
const relationshipOptions = [
  [
    { text: '配偶', value: 1 },
    { text: '父亲', value: 2 },
    { text: '母亲', value: 3 },
    { text: '儿子', value: 4 },
    { text: '女儿', value: 5 },
    { text: '兄弟', value: 6 },
    { text: '姐妹', value: 7 },
    { text: '祖父', value: 8 },
    { text: '祖母', value: 9 },
    { text: '外祖父', value: 10 },
    { text: '外祖母', value: 11 },
    { text: '孙子', value: 12 },
    { text: '孙女', value: 13 },
    { text: '外孙', value: 14 },
    { text: '外孙女', value: 15 },
    { text: '岳父', value: 16 },
    { text: '岳母', value: 17 },
    { text: '公公', value: 18 },
    { text: '婆婆', value: 19 },
    { text: '女婿', value: 20 },
    { text: '儿媳', value: 21 },
    { text: '朋友', value: 22 },
    { text: '同事', value: 23 },
    { text: '邻居', value: 24 },
    { text: '其他', value: 25 }
  ]
]

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入本人姓名' },
    { min: 2, max: 20, message: '姓名长度应在2-20个字符之间' }
  ],
  idNumber: [
    { required: true, message: '请输入本人证件号码' }
  ],
  emerName: [
    { required: true, message: '请输入紧急联系人姓名' },
    { min: 2, max: 20, message: '姓名长度应在2-20个字符之间' }
  ],
  emerTel: [
    { required: true, message: '请输入联系人电话' },
    { 
      validator: (value: string) => /^1[3-9]\d{9}$/.test(value) || /^0\d{2,3}-?\d{7,8}$/.test(value), 
      message: '请输入正确的电话号码格式' 
    }
  ],
  relationship: [
    { required: true, message: '请选择与本人关系' }
  ]
})

// 获取关系文本 - 用于列表显示
const getRelationshipText = (value: number) => {
  const option = relationshipOptions[0].find(item => item.value === value)
  return option ? option.text : '未选择'
}

// 电话号码输入验证
const onPhoneInput = (value: string) => {
  phoneError.value = ''
  
  // 验证手机号或固话格式
  if (value && value.length >= 7) {
    const isMobile = /^1[3-9]\d{9}$/.test(value)
    const isLandline = /^0\d{2,3}-?\d{7,8}$/.test(value)
    
    if (!isMobile && !isLandline) {
      phoneError.value = '请输入正确的手机号或固话格式'
    }
  }
}



// 新增记录
const addRecord = () => {
  isEdit.value = false
  showForm.value = true
  resetFormData()
}

// 编辑记录
const editRecord = (record: any, index: number) => {
  isEdit.value = true
  editIndex.value = index
  showForm.value = true
  form.value = { ...record }
}

// 删除记录
const deleteRecord = (index: number) => {
  Taro.showModal({
    title: '确认删除',
    content: '确定要删除这个紧急联系人吗？',
    success: (res) => {
      if (res.confirm) {
        recordList.value.splice(index, 1)
        Taro.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 取消表单
const cancelForm = () => {
  showForm.value = false
  resetFormData()
}

// 重置表单数据
const resetFormData = () => {
  form.value = {
    id: '',
    name: '',
    idNumber: '',
    emerName: '',
    emerTel: '',
    relationship: 1,
    note: '',
    recordid: 0,
    createBy: '',
    createTime: '',
    updateBy: '',
    updateTime: ''
  }
  phoneError.value = ''
}

// 重置表单
const resetForm = () => {
  Taro.showModal({
    title: '确认重置',
    content: '确定要重置表单吗？所有已填写的信息将被清空。',
    success: (res) => {
      if (res.confirm) {
        resetFormData()
        Taro.showToast({
          title: '表单已重置',
          icon: 'success'
        })
      }
    }
  })
}

// 提交表单
const submitForm = async () => {
  try {
    submitting.value = true
    
    await formRef.value.validate()
    
    // 清除错误信息
    phoneError.value = ''
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 设置时间戳
    const now = new Date().toISOString()
    if (isEdit.value) {
      // 编辑模式
      form.value.updateTime = now
      recordList.value[editIndex.value] = { ...form.value }
      Taro.showToast({
        title: '修改成功',
        icon: 'success'
      })
    } else {
      // 新增模式
      form.value.id = Date.now().toString()
      form.value.createTime = now
      recordList.value.push({ ...form.value })
      Taro.showToast({
        title: '添加成功',
        icon: 'success'
      })
    }
    
    showForm.value = false
    resetFormData()
    
  } catch (error) {
    Taro.showToast({
      title: '请完善必填信息',
      icon: 'error'
    })
  } finally {
    submitting.value = false
  }
}

// 页面加载时获取数据
Taro.useLoad(() => {
  // 这里可以调用API获取数据
  console.log('页面加载，获取紧急联系人信息数据')
})
</script>